package de.ishuo.netzclubminutecounter;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MinuteCounter {
	
	private static Pattern DATE_PATTERN = Pattern.compile("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d");
	private static Pattern TIME_PATTERN = Pattern.compile("\\d\\d:\\d\\d\\:\\d\\d");

	public static int countMinute(File file) {
		String extension = getExtension(file);
		if (!extension.equalsIgnoreCase("pdf")) {
			System.out.println(file + " not pdf. Ignored.");
			return 0;
		}
		
		String text = PdfBoxTextExtractor.extractText(file);
		
		int minute = 0;
		String[] lines = text.split("\n");
		for (String line : lines) {
			if (startsWithDate(line)) {	
				String duration = extractDuration(line);
				if (!duration.isEmpty()) {
					minute += parseToMinute(duration);
				}
			}
		}
		
		return minute;
	}

	private static String getExtension(File file) {
		String filename = file.getName();
		int lastPoint = filename.lastIndexOf(".");
		String extension = filename.substring(lastPoint + 1);
		return extension;
	}
	
	private static boolean startsWithDate(String line) {
		Matcher matcher = DATE_PATTERN.matcher(line);
		return matcher.lookingAt();
	}
	
	private static String extractDuration(String line) {
		Matcher matcher = TIME_PATTERN.matcher(line);
		matcher.find();
		if (matcher.find()) {
			return matcher.group();
		} else {
			return "";
		}
	}
	
	private static int parseToMinute(String duration) {
		String hourString = duration.substring(0, 2);
		int hour = Integer.parseInt(hourString);
		
		String minString = duration.substring(3, 5);
		int min = Integer.parseInt(minString);
		
		String secString = duration.substring(6, 8);
		int sec = Integer.parseInt(secString);
		
		int result = 60 * hour + min;
		// Less than a minute is rounded up to a minute
		if (sec > 0) result++;
		
		return result;
	}



	public static void main(String[] args) {
		File file = new File("test/res/entgeld.pdf");
//		MinuteCounter counter = new MinuteCounter(file);
		System.out.println(MinuteCounter.countMinute(file));
		
		
		String test = "07.03.2011 11:48:34 017683075714 00:00:04 0,00";
		Pattern pattern = Pattern.compile("\\d\\d:\\d\\d\\:\\d\\d");
		Matcher matcher = pattern.matcher(test);
//		String regex = "^(07)";
//		boolean doesMatch = test.matches(regex);
		matcher.find();
		matcher.find();
//		String time = matcher.group();
//		counter.parseToMinute(time);

		
	}
	
	
}
